package com.iwat.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iwat.mapper.UserMapper;
import com.iwat.pojo.User;
import com.iwat.vo.DictItemVo;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author wangweiqiang
 * @Classname UserServiceImpl
 * @Date 2023/9/22 10:08
 * @Description
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements com.iwat.service.UserService {

    private static final String REDIS_CACHE_PREFIX = "Dict:";

    private RedisTemplate redisTemplate;

    @Override
    public List<User> queryUser() {
        return this.list();
    }

    @Override
    public String queryTranslation(String dictCode, String key) {
        return queryTranslationInternal(dictCode, null, null, key);
    }

    @Override
    public String queryTranslationForeign(String dictCode, String dictText, String dictTable, String key) {
        return queryTranslationInternal(dictCode, dictText, dictTable, key);
    }

    private String queryTranslationInternal(String dictCode, String dictText, String dictTable, String key) {
        String redisKey = REDIS_CACHE_PREFIX.concat(dictTable == null ? "" : dictTable.concat(":")).concat(dictCode);
        Map entries = redisTemplate.opsForHash().entries(redisKey);
        if (!entries.isEmpty()){
            return (String) entries.get(key);
        }
        // 从数据库中查询
        List<DictItemVo> dictItemVos = (dictTable == null) ? baseMapper.queryTranslation(dictCode) : baseMapper.queryTranslationForiegn(dictCode, dictText, dictTable, key);
        Map<String, String> dictItems = dictItemVos.stream().collect(Collectors.toMap(DictItemVo::getItemValue, DictItemVo::getItemText));
        redisTemplate.opsForHash().putAll(redisKey, dictItems);
        redisTemplate.expire(redisKey,5, TimeUnit.MINUTES);
        return dictItems.get(key);
    }

    @Override
    public IPage<User> queryPage() {
        IPage<User> page = new Page(1,10);
        return this.page(page);
    }


    @Override
    public List<User> testListWithJoin() {
        return baseMapper.testListWithJoin();
    }
}
